<?php
/**
 * Created by PhpStorm.
 * Date: 2017/8/31
 * Time: 下午12:05
 * Author: kkk
 */

use App\Services\FileUploadService;
use App\Services\OssService;
use App\Api\Helper\ReturnMessage;
use OSS\OssClient;
use App\Models\Messages;
use App\Models\MessageUsers;





/**
 * 重组数组方法
 */




/**
 * 公共上传图片方法
 */
if (!function_exists('uploadByOss'))
{
    function uploadByOss($fileName)
    {
        $bucket = "qkw-api";   //阿里云存储桶名称
        $filePath = './image/';  //存储路径
        $ext = "";     //获取文件扩展名
        $path = "";  //图片全路径 包含文件名

        $upload = new FileUploadService();
        $upload->set('path',$filePath);
        $upload->set('israndname', true);
        $upload->upload($fileName);
        $file = $upload->getFileName();
        //获取文件名以及后缀
        if (!is_array($file)) {
            $fileName = pathinfo($file, PATHINFO_FILENAME);
            $ext = pathinfo($file, PATHINFO_EXTENSION);
        }

        if (!$file) return $upload->getErrorMsg();
        $allImage = OssService::getAllObjectKey($bucket);  //获取阿里云oss所有文件

        //多文件上传
        if (is_array($file))
        {
            $len = count($file);
            $url = array();

            for ($i = 0; $i < $len; $i++)
            {
                $path = $filePath.$file[$i];

                $fileName = pathinfo($file[$i], PATHINFO_FILENAME);
                $ext = pathinfo($file[$i], PATHINFO_EXTENSION);
                $newFileName = "";

                foreach ($allImage as $v)
                {
                    if ($v == $file[$i])
                    {
                            $file[$i] = $file[$i];
                            $newFile = $fileName.time().'.'.$ext;
                            $newFileName = $filePath.$newFile;
                            if (rename($filePath.$file[$i],$newFileName))
                            {
                                 $file[$i] = $newFile;
                                 $path = $newFileName;
                             }
                    }
                }

                        if (OssService::publicUpload($bucket,$file[$i],$path))
                            $url[] = OssService::getPublicObjectURL($bucket,$file[$i]);
                        @unlink($path);
            }
            return $url;
        }

        //单文件上传
        for ($i = 0; $i < count($allImage); $i++)
        {
            if ($file == $allImage[$i]) $file = $file;
        }

        $newFile = $fileName.time().'.'.$ext;
        $newFilepath = $filePath.$newFile;
        if (rename($filePath.$file, $newFilepath))
        {
            $path = $newFilepath;
            $file = $newFile;
        }
        if (OssService::publicUpload($bucket, $file, $path))
        {
            $url = OssService::getPublicObjectURL($bucket, $file);
            @unlink($path);
            return $url;
        }
        return ReturnMessage::success('上传失败,请重新上传');
    }
}
/**
 * @name  公共上传方法方法
 * @ps 暂时支持单文件上传方式  - 没有来的及封装呢
 * @user iHammer
 */
if (!function_exists('uploadToOss'))
{
    function uploadToOss($fileName,&$errmsg,$type_model='image',$filePath="image/"){
        //不同文件有着不同的数据处理
        $type_array = ['video','image','voice'];
        if(!in_array($type_model,$type_array)){
            $errmsg = '上传所属模型出现问题！';
             return false;
        }
        if(empty($_FILES)){
             $errmsg = '没有发现上传文件！';
             return false;
        }
        if(empty($_FILES[$fileName])){
            $errmsg = '没有发现上传文件！';
            return false;
        }
        $bucket = "miyupp";///阿里云存储桶名称
        $filePath = trim($filePath,'/').'/';
        if($type_model=='video'){
            $maxsize = 524288000;
            $file_type = array('mp4','mov','MOV');//上传文件类型
            $filePath = trim("video/",'/').'/';
        }elseif($type_model=='image'){
            $maxsize = 26214400;
            $file_type = array('jpg','gif','png','jpeg');//上传文件类型
            $filePath = trim("image/",'/').'/';
        }elseif($type_model=='voice'){
            $maxsize = 26214400;
            $file_type = array('mp3','wav','flac');//上传文件类型
            $filePath = trim("voice/",'/').'/';
        }
        $name = $_FILES[$fileName]['name']; //上传文件的文件名 'Chrysanthemum.jpg'
        $tmp_name = $_FILES[$fileName]['tmp_name']; //服务器端临时文件存放路径 'D:\wamp\tmp\php71E6.tmp'
        $size = $_FILES[$fileName]['size']; //上传文件的大小 879394   858 KB (879,394 字节)
        $error = $_FILES[$fileName]['error']; //错误信息 0*/
        $type = $_FILES[$fileName]['type'];

        if($error!=0){
            $errmsg = '未知的错误！';
            return false;
        }
        $type = substr(strrchr($name, '.'), 1);
        //$type = strrev(strchr(strrev($type),'/',true));
        if(is_array($name)){
            $errmsg = '暂时不支持多文件上传！';
            return false;
        }
        //验证类型
        if (!in_array(strtolower($type),$file_type)) {
            $errmsg = "上传文件类型不正确。";
            return false;
        }
        //验证大小
        if($size>$maxsize){
             $errmsg = "文件过大,上传的文件不能超过{$maxsize}个字节";
            return false;
        }

        //重新命名文件
        $fileName = $filePath.date('YmdHis')."_".rand(1000,9999).'.'.$type;

        $accessKeyId = "LTAIL1feFcYv7aRM";
        $accessKeySecret = "lFRP2PfNnGbHYYqKUUpdTmPvo8cXeR";
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
        $object = $fileName;
        $file = $tmp_name;
        $options = array(
            OssClient::OSS_CHECK_MD5 => true,
            OssClient::OSS_PART_SIZE => 1,
        );
        try{
            $ossclient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossclient->multiuploadFile($bucket, $object, $file, $options);
            $url = OssService::getPublicObjectURL($bucket, $fileName,"https://file.ihammer.cn");
            return $url;
        } catch(\OSS\Core\OssException $e) {
            $errmsg = $e->getMessage();
            return false;
        }
    }
}






/**
 * 重组数组方法
 */

if (!function_exists('resetField')) {
    function resetField($fname,$data)
    {
        if(!$data){
//            echo ReturnMessage::success('数据查询失败','1002');die;
            return array();
        }
        return \App\Services\ResetDataService::ResetData($fname,$data);
    }
}

/**
 * 重组二维数组
 */
if (!function_exists('resetFieldArr')) {
    function resetFieldArr($fname,$data)
    {
        if(!$data){
//            echo ReturnMessage::success('数据重组失败','1002');die;
            return array();
        }
        foreach($data as $k=>$v){
            $data[$k]=resetField($fname,$v);
        }
        return $data;
    }
}



//获取当前请求的路由路径


if (!function_exists('getRouteUrl')) {
    function getRouteUrl(){
        return Request::path();
    }
}


/**
 * @type string  日志类型   debug|info|notice|warning|error|critical|alert.
 * @content string  日志内容
 */
if (!function_exists('logStore')) {
    function logStore($type,$content){
        \Log::$type(getRouteUrl(),array('context'=>$content.'-time:'.time().'-ip:'.\Request::getClientIp()));
    }
}

/**
 * 生成随机字符串
 */
if (!function_exists('rand_str')) {
    function rand_str($len)
    {
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $string=time();
        for(;$len>=1;$len--)
        {
            $position=rand()%strlen($chars);
            $position2=rand()%strlen($string);
            $string=substr_replace($string,substr($chars,$position,1),$position2,0);
        }
        return $string;
    }
}

if (!function_exists('Request_url')) {
    /**
     * @param $url 请求网址
     * @param bool $params 请求参数
     * @param int $ispost 请求方式
     * @param int $https https协议
     * @return bool|mixed
     */
    function Request_url($url, $params = false, $ispost = 0, $https = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        $response = curl_exec($ch);

        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
}

if (!function_exists('json_format_protect')) {
    function json_format_protect(&$val)
    {
//        dd(2);
        if($val!==true && $val!==false && $val!==null)
        {
            $val = urlencode($val);
        }
    }
}


